import { Jx, Jpp } from "./Jx"
import { Dialog } from "./Dialog"


// const c_url = "http://192.168.0.109:8080/";
const c_url = "http://www.baidu.com:8080/";
const c_localurl = "http://192.168.0.109:8080/";

// const c_image = "https://unsplash.it/400/400?image=";s

// 默认 POST T(有token) D(有错误提示) R(retain无圈圈)
export const NET_NR = 1; // 无retain
export const NET_RI = 1; // 有retain(圈圈)
export const NET_NT = 1; // 无token
export const NET_ND = 1; // 无错误提示
export const NET_STR = 1; // stringify 模式
export const NET_GET = 1; // GET 模式

const c_strReq = "网络请求: ";
const c_strRes = "请求结果: ";
const c_strErr = "请求捕获: ";
const c_space = "    ";
// 网络 附带转圈圈效果
export class Net{

    static _url = c_url;
    static switchUrl(){
        if(this._url == c_url){
            this._url = c_localurl;
            console.log("切换到本地服务器");
        }else{
           this. _url = c_url;
           console.log("切换到正式服务器");
        }
    }

    // 请求 app版本 过审状态
    static fetVersion(versionName){
        return new Promise((resolve, reject)=>{
            console.log("请求版本: advice/version");
            fetch(this._url + "advice/version", { headers : {}, method : 'GET' }).then(r=>r.json())
            .then(r=>{
                let url = "";
                let applied = 0;
                if(!r.success){
                    console.warn(Jx.stringify(r));
                    console.log(Jx.stringify(r));
                    resolve({url, applied});
                    return;
                }
                console.warn(Jx.stringify(r.data));
                console.log(Jx.stringify(r.data));
                let { version, iosversion, android, ios, apply, android_apply, ...other } = r.data;
                if(Jpp.isAndroid){
                    if(version != versionName){
                        url = android;
                    }
                    applied = ((!android_apply) || (android_apply != "0")) ? 1 : 0;
                }else{
                    if(iosversion != versionName){
                        url = ios;
                    }
                    applied = ((!apply) || (apply != "0")) ? 1 : 0;
                }
                resolve({url, applied, ...other});
            }).catch(err=>reject(err));
        })
    }

    static _token = null;
    // 请求角色（粉丝/代理/运营商）
    static fetRole(token){
        return fetch(this._url + "team/myRole", { headers : { token }, method : 'POST' }).then(r=>r.json());
    }


    static toBody(obj){
        if(!obj){
            return null;
        }
        if(Jx.isObjectEmpty(obj)){
            return null;
        }
        let body = new FormData();
        for (const key in obj) {
            body.append(key,obj[key]);
        }
        return body;
    }

    static toPostGet(method, obj, token){
        let headers = token ? { token } : {};
        let body = this.toBody(obj);
        return body ? { method, headers, body } : { method, headers };
    }

    // 请求结果
    static isSuccess(r, url, toast){
        if(!r){
            console.warn(c_strRes + url + c_space + "非结果");
            if(toast){
                Dialog.toast("网络超时");
            }
            return false;
        }
        if(r.success){
            if(r.data){
                console.log(c_strRes + url + c_space + Jx.stringify(r.data));
            }else{
                console.log(c_strRes + url + c_space + Jx.stringify(r));
            }
            return true;
        }
        if(r.status){
            console.warn(c_strRes + url + c_space + "error status: " + r.status);
            if(toast){
                Dialog.toast("服务器超时");
            }
            return false;
        }
        if (r.error){
            console.warn(c_strRes + url + c_space + Jx.stringify(r.error));
            if(toast){
                if(Jx.isString(r.error)){
                    Dialog.toast(r.error);
                } else if(Jx.isObject(r.error)){
                    if(r.error.errMsg){
                        Dialog.toast(r.error.errMsg);
                    }else{
                        Dialog.toast("请求超时");
                    }
                }
            }
        }
        return false;
    }

    // 请求 已处理失败的逻辑, 自己维护成功的逻辑即可
    static request(url, obj, cfg){
        if(obj){
            console.log(c_strReq + url + c_space + "body: " + JSON.stringify(obj));
        }else{
            console.log(c_strReq + url);
        }
        if(Jx.isUndefined(cfg)){
            cfg = {};
        }
        if(cfg.NET_STR){
            obj = JSON.stringify(obj);
            console.log(c_strReq + url + c_space + "stringify: " + obj);
            obj = { headers : {token : this._token }, method : 'POST', body : obj };
        }else{
            obj = this.toPostGet(cfg.NET_GET ? 'GET' : 'POST', obj, cfg.NET_NT ? null : this._token);
        }
        if(cfg.NET_NR){
        }else if(cfg.NET_RI){
            Dialog.retain(true);
        }else{
            Dialog.retain(false);
        }
        const add = cfg.params ? cfg.params.add : null;
        const freshed = cfg.freshed;
        return new Promise((resolve, reject)=>{
            fetch(this._url + url, obj).then(r=>r.json()).then(r=>{
                if(cfg.NET_NR){
                }else{
                    Dialog.release();
                }
                freshed && freshed();
                if(this.isSuccess(r, url, cfg.NET_ND ? false : true)){
                    resolve(r);
                }else{
                    add && add()
                    reject && reject(null);
                }
            }).catch(err=>{
                if(cfg.NET_NR){
                }else{
                    Dialog.release();
                }
                freshed && freshed();
                add && add()
                console.warn(c_strErr + c_space + Jx.stringify(err))
                if(!NET_ND){
                    Dialog.toast("网络超时");
                }
                reject && reject(err);
            })
        })
    }
}